import React, { Component } from 'react';
import './login.scss'
class App extends Component {
  state={
    phoneNum:'',// 手机号
    matchNum:'',// 验证码
    checked:false,//选中框状态
    err_msg:'',// 错误信息
  }
  /* 三个表单改变状态的函数 */
  handleChange = (e)=>{
    let {type,key} = e.target.dataset;
    let value = '';
    if(type === 'checkbox'){
      value = e.target.checked
    }else{
      value = e.target.value;
    }
    this.setState(preState=>{
      return {
        [key]:value
      }
    })
  }

  /* 手机号验证 */
  validatePhoneNum = (phoneNum)=>{
    // 如果手机号为空
    if(!phoneNum){
      this.setState({
        err_msg:'请输入手机号',
      });
      return false;
    }
    // 手机号码验证
    if(!/^1[3|4|5|7|8][0-9]{9}$/.test(phoneNum)){
      this.setState({
        err_msg:'手机号格式有误,请更改后重试'
      });
      return false;
    }
    // 验证成功返回true
    return true;
  }
  /* 登录验证 */
  handleLogin = ()=>{
    let phoneNum = this.state.phoneNum;
    let valid = this.validatePhoneNum(phoneNum);
    if(!valid){
      return false
    }else {
      console.log('正确');
      this.setState({
        err_msg:''
      })
    };
  }
  render() {
    return (
      <div className='login'>
        <div className="phone">
          <input type="text" placeholder="请输入手机号"
          value={this.state.phoneNum}
          data-type='text'
          data-key='phoneNum'
          onChange={this.handleChange} />
        </div>
        <div className="match">
          <input type="text" placeholder="请输入短信验证码"
          value={this.state.matchNum}
          data-type='number'
          data-key='matchNum'
          onChange={this.handleChange} />
          <span className='getMatchNum'>获取验证码</span>
        </div>
        {/* 警告提示 */}
        <div className='warning'>
          {
            this.state.err_msg?<span className='err-msg'>{this.state.err_msg}</span>:''
          }
        </div>

        <div className='other-item'>
          <a href="javascript">遇到问题?</a>
          <span>使用密码验证登录</span>
        </div>
        <div className="loginBtn" onClick={this.handleLogin}>登录</div>
        <div className="msg">
          <input type="checkbox" name="" id=""
           value={this.state.checked}
           data-type='checkbox'
           data-key='checked'
           onChange={this.handleChange} />
          <span>我同意</span>
          <a href="javascript">《服务条款》</a>
          <span>和</span>
          <a href="javascript">《网易隐私政策》</a>
        </div>
      </div>
    );
  }
}

export default App;
